package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.model.Donor;
import com.cipe.cmrs.service.DonorService;

@Controller
public class DonorController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;

	@Autowired
	private DonorService donorService;
	
	@RequestMapping("/secure/showAddDonor.do")
	public String showAddDonor(Model model) {
		model.addAttribute("donor", new Donor());
		return "editDonor";
	}
	
	@RequestMapping("/secure/showEditDonor.do")
	public String showEditDonor(@RequestParam Integer id, Model model) {
		model.addAttribute("donor", donorService.findById(id));
		return "editDonor";
	}
	
	@RequestMapping("/secure/saveDonor.do")
	public String SaveDonor(@ModelAttribute("donor") Donor donor, BindingResult result, Model model, HttpServletRequest request) {
		
		if(donorService.saveDonor(donor, getUserId(request)) == null){
			result.reject("editDonor.message.error");
		} else {
			result.rejectValue("id", "editDonor.message.success");
		}
		model.addAttribute("donor", donor);	
		return "editDonor";
	}
	
	@RequestMapping("/secure/showDonorList.do")
	public String showDonorList(Model model) {
		model.addAttribute("donors", donorService.findAll());
		return "donorList";
	}
}
